package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.RoleDTO;
import com.lastproject.ejb.entities.Role;
import com.lastproject.ejb.util.RoleConversion;

/**
 * Lazar Mihnea
 */
@Stateless
public class RoleDAO implements RoleDAORemote {

	@PersistenceContext
	private EntityManager em;

	@EJB
	RoleConversion conv;
	
    public RoleDAO() {

    }

	@Override
	public void create(RoleDTO entity) {
		em.persist(conv.fromDTO(entity));
		
	}

	@Override
	public void edit(RoleDTO entity) {
		em.merge(conv.fromDTO(entity));
		
	}

	@Override
	public void remove(RoleDTO entity) {
		Role r = null;
		if ((r = em.find(Role.class, conv.fromDTO(entity).getId())) == null) {
			em.remove(em.merge(r));
		}
		
	}

	@Override
	public RoleDTO findById(Object id) {
		Role r = em.find(Role.class, id);
		RoleDTO role = conv.fromEntity(r);
		return role;
	}

	@Override
	public List<RoleDTO> findAll() {
		List<Role> rList = em.createQuery("SELECT r from Role r", Role.class).getResultList();
		List<RoleDTO> rdtoList = new ArrayList<RoleDTO>();
			for (Role r : rList) {
				rdtoList.add(conv.fromEntity(r));
			}
		return rdtoList;
	}

}
